package com.car.action.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.car.action.util.CommonController;
import com.car.backend.opensource.AlipayConfig;
import com.car.backend.opensource.AlipayNotify;
import com.car.backend.opensource.GetWxOrderno;
import com.car.backend.opensource.IosVerifyUtil;
import com.car.common.model.MessageUnreadNum;
import com.car.common.model.Users;
import com.car.common.model.VipPackage;
import com.car.common.model.VipRecord;
import com.car.job.TheadImgCheck;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.utils.APIJSON;
import com.utils.RongCloudUtil;
import com.utils.StringUtil;
import com.utils.SystemClock;
import com.utils.Toolkit;


public class CallbackController extends CommonController {
	
	private static Logger logger = Logger.getLogger(CallbackController.class);
	
	/**
	 * 苹果内购
	 */
	@Before(Tx.class)
	public void apple_pay() {
		/*
		byte[] bytes = Base64.decode(getPara("apple_receipt"));
		
		String apple_receipt = new String(bytes);
		System.out.println("BASE64解密：" + apple_receipt);
		*/
		String apple_receipt = getPara("apple_receipt");
		String verifyResult = IosVerifyUtil.buyAppVerify(apple_receipt, 1);
		if (verifyResult == null) {
			renderText(APIJSON.result(1067));
			return;
		} else { // 苹果验证有返回结果
			JSONObject job = JSONObject.parseObject(verifyResult); 
			String status = job.getString("status");
			RongCloudUtil.sendTxt("141", "140901", job.toJSONString());
			if("21007".equals(status)){	//是沙盒环境，应沙盒测试，否则执行下面	
				verifyResult = IosVerifyUtil.buyAppVerify(apple_receipt,0);
				System.out.println("沙盒环境，苹果平台返回JSON:"+verifyResult);
				job = JSONObject.parseObject(verifyResult); 
				status = job.getString("status");
			}
			if (status.equals("0")){
				if (StringUtil.empty(getPara("package_id"))) {
					renderJson(APIJSON.result(4001));
					return;
				}
				
				String package_id = getPara("package_id");
				VipPackage vipPackage = VipPackage.dao.findById(package_id);
				/*
				com.alibaba.fastjson.JSONArray in_app = job.getJSONArray("in_app");
				if (in_app.size() == 0) {
					renderJson(APIJSON.result(6666));
					return;
				} else {
					String product_id = in_app.getJSONObject(0).getString("product_id");
					if (!product_id.equals(vipPackage.getStr("apple_pay_id"))) {
						renderJson(APIJSON.result(6666));
						return;
					}
				}
				*/
				Long user_id = super.getUserId();
				String order_num = Toolkit.newTradeNo();
				VipRecord download_vip = VipRecord.dao.findFirst("select id from vip_record where download_id = " + job.getJSONObject("receipt").getLong("download_id")+ " order by id desc limit 1 ");
				if(download_vip != null){
					renderText(APIJSON.result(6012));
					return;
				}
				if (vipPackage.getType() == 1) {
					VipRecord one = new VipRecord();
					one.setUserId(user_id.intValue());
					one.setOrderNum(order_num);
					one.setTransactionNum(apple_receipt);
					one.setTitle(vipPackage.getTitle());
					one.setBuyType("User");
					one.setZsHot(vipPackage.getZsHot());
					one.setTime(Integer.valueOf(vipPackage.getDays()));
					one.setPrice(vipPackage.getPrice());
					one.setStatus(2);
					one.setOrderType(1);
					one.setVipPackageId(vipPackage.getId());
					one.setCreateTime(SystemClock.now()/1000L);
					one.setUpdateTime(SystemClock.now()/1000L);
					one.setReceiptCreationDateMs(job.getJSONObject("receipt").getLong("receipt_creation_date_ms"));
					one.setDownloadId(job.getJSONObject("receipt").getLong("download_id"));
					one.save();
				} else {
					VipRecord one = new VipRecord();
					one.setUserId(user_id.intValue());
					one.setOrderNum(order_num);
					one.setTransactionNum(apple_receipt);
					one.setTitle("热度充值" + vipPackage.getTitle() );
					one.setBuyType("User");
					one.setZsHot(vipPackage.getZsHot());
					one.setHot(vipPackage.getHot());
					one.setTime(0);
					one.setPrice(vipPackage.getPrice());
					one.setStatus(2);
					one.setOrderType(2);
					one.setVipPackageId(vipPackage.getId());
					one.setCreateTime(SystemClock.now()/1000L);
					one.setUpdateTime(SystemClock.now()/1000L);
					one.setReceiptCreationDateMs(job.getJSONObject("receipt").getLong("receipt_creation_date_ms"));
					one.setDownloadId(job.getJSONObject("receipt").getLong("download_id"));
					one.save();
				}
				boolean result = record(order_num,"ApplePay","");
				if (result) {
					renderText(APIJSON.result(0));
					return;
				} else {
					renderText(APIJSON.result(1048));
					return;
				}
			}else {
				renderText(APIJSON.result(1048));
				return;
			}
		}
	}
	
	public void alipay() {
		HttpServletRequest request =  getRequest();
		HttpServletResponse response =  getResponse();
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		
		 
		System.out.println("alipay callback params :"+params);
		logger.info("alipay callback params :"+params);
		
		String result = "fail";
		try {
			//支付宝交易号
			String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
			
			//商户订单号
			String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
			//交易状态
			String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
			System.out.println("record trade_status : " + trade_status);
			boolean flag = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_kek2,"utf-8","RSA2");
			if (flag) {
				if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
					result = record(out_trade_no,"Alipay",trade_no)?"success":"fail";
				}
			}
//			if(AlipayNotify.verify(params)){//验证成功
//				if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
//					System.out.println("Alipay record trade_status : " + trade_status);
//					result = record(trade_no,"Alipay",out_trade_no)?"success":"fail";
//				}
//			}
			//boolean flag = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, "UTF-8","RSA2");
//			System.out.println(flag);
		} catch (Exception e1) {
			e1.printStackTrace();
		} 
		response.setContentType("text/html;charset=utf-8");
	    try {
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	    renderText(result);
	}
	
	/**
	 * Url         : POST /callback/apple_pay
		Controller  : com.car.action.api.CallbackController.(CallbackController.java:1)
		Method      : apple_pay
		Parameter   : apple_receipt=MIIT2wYJKoZIhvcNAQcCoIITzDCCE8gCAQExCzAJBgUrDgMCGgUAMIIDfAYJKoZIhvcNAQcBoIIDbQSCA2kxggNlMAoCAQgCAQEEAhYAMAoCARQCAQEEAgwAMAsCAQECAQEEAwIBADALAgEDAgEBBAMMATEwCwIBCwIBAQQDAgEAMAsCAQ8CAQEEAwIBADALAgEQAgEBBAMCAQAwCwIBGQIBAQQDAgEDMAwCAQoCAQEEBBYCNCswDAIBDgIBAQQEAgIAnzANAgENAgEBBAUCAwHV7TANAgETAgEBBAUMAzEuMDAOAgEJAgEBBAYCBFAyNTIwGAIBBAIBAgQQ4jyENKjIN9rRj3kXr4M+eDAbAgEAAgEBBBMMEVByb2R1Y3Rpb25TYW5kYm94MBwCAQUCAQEEFGD1KwA4IdhJbGAXAgaCCPfDFEI1MB4CAQICAQEEFgwUY29tLndjcy5maWZ0eURlZ3JlZXMwHgIBDAIBAQQWFhQyMDE5LTA2LTE0VDAy...  order_type=2  package_id=9  token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJBUFAiLCJ1c2VyX2lkIjoiMTQwOTAxIiwiaXNzIjoiU2VydmljZSIsImV4cCI6MTU5MTc2NzM0OCwiaWF0IjoxNTYwMjMxMzQ4fQ._BXT-MqK9yDhk-Lc5-H1-IDONk1b_4g19WGxTe-akRA
	 */
	public void test() {
		String trade_no = getPara("trade_no");
		String transaction_num = getPara("transaction_num");
		record(trade_no,"Alipay",transaction_num);
		//gmt_create=2019-09-06 09:06:26  charset=utf-8  seller_email=925393329@qq.com  subject=????51800?  sign=bsRFuoR6+HmanPuXdF54CxErBa8KwC71mm9d157yjg5TuHzZLV0BHhvswOPWh1P1pu83dWlMIBQMqAF6J2jzXYfRXXpOH13LRiw4AmXvwKHaWM5krMblE4dQHTbYRiZYSugTI0wrHThUOIb7RUZsS9nw8JqnOLSD9YSzGnC6BD6pbvB3hk2O1oBx7uWKxclpJnN/S8Z8ngqnnTj01N2QPudA5Im6v/INurWnZpieWmEoixx/+JOe6io5PSIaSaHylK/NAQPQORmEk59737waGGNANAxdQ2dGeZun2bKqA8ESciSAPm71U8TJgWgjbZS9npOoXkP07/HmTBQBG5XZmA==  body=????51800?  buyer_id=2088002683567344  invoice_amount=0.01  notify_id=2019090600222090627067341048340485  fund_bill_list=[{"amount":"0.01","fundChannel":"ALIPAYACCOUNT"}]  notify_type=trade_status_sync  trade_status=TRADE_SUCCESS  receipt_amount=0.01  app_id=2019051764991555  buyer_pay_amount=0.01  sign_type=RSA2  seller_id=2088531254487135  gmt_payment=2019-09-06 09:06:27  notify_time=2019-09-06 09:06:27  version=1.0  out_trade_no=67731979490169291125489E  total_amount=0.01  trade_no=2019090622001467341050641818  auth_app_id=2019051764991555  buyer_logon_id=892***@qq.com  point_amount=0.00  
		//2019090622001467341050641818
		renderText("1");
	}
	
	private boolean record(String trade_no, String pay_type,String transaction_num) {
		boolean result = false;
		VipRecord one = VipRecord.dao.findFirst("select * from vip_record where order_num = '"+ trade_no +"' order by id desc limit 1 ");
		if(one != null) {
			if (one.getStatus() != 2) {
				
			} else {
				try {
					System.out.println("trade_no callback start");
					int order_type = one.getOrderType(); 
					int user_id = one.getUserId();
					Users users = Users.dao.findById(user_id);
					// 会员充值
					if (order_type == 1) {
						int zs_hot = one.getZsHot();
						long time = one.getTime() * 86400L;
						if (users.getVipEndTime() == null || users.getVipEndTime() == 0L  || users.getVipEndTime() < (SystemClock.now() /1000L)) {
							time = SystemClock.now() /1000L + time;
						} else {
							time = users.getVipEndTime() + time;
						}
						Db.update("update users set vip_end_time = " + time +",hot_val = hot_val+ "+ zs_hot +" where id = " + user_id);
						Db.update("update vip_record set buy_type = '" + pay_type +"' , transaction_num = '" + transaction_num +"',status = 1 where id = " + one.getId());
						
						if (one.getPrice().intValue() == 98) {
							Db.update("update users set vip_badpe = 1 where id = " + user_id);	
						} else if (one.getPrice().intValue() == 198) {
							Db.update("update users set vip_badpe = 2 where id = " + user_id);
						} else if (one.getPrice().intValue() == 298) {
							Db.update("update users set vip_badpe = 3 where id = " + user_id);
						}
						MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_ORDER, user_id);
						result = true;
					} else if (order_type == 2) {
						double rate  = 1; 
						if ("ApplePay".equals(pay_type)) {
							rate = 0.7;
						}
						int hot = new Double(one.getHot()* rate).intValue();
						hot = hot + one.getZsHot();
						Db.update("update users set hot_val = hot_val+ "+ hot +" where id = " + user_id);
						Db.update("update vip_record set buy_type = '" + pay_type +"' , transaction_num = '" + transaction_num +"',status = 1 where id = " + one.getId());
						MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_ORDER, user_id);
						result = true;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		} else {
			return true;
		}
		return result;
	}

	public void wxpay() {
		HttpServletRequest request =  getRequest();
		HttpServletResponse response =  getResponse();
		String result = "SUCCESS";
		try {
	    	   BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
		       String line = null;
		       StringBuilder sb = new StringBuilder();
		       while((line = br.readLine())!=null){
		           sb.append(line);
		       }
			   String sbStr = sb.toString();
			   logger.info("wx callback: " + sbStr);
	           Map params = GetWxOrderno.doXMLParse(sbStr);
	           String return_code  = (String) params.get("return_code");
	           if("SUCCESS".equals(return_code)){
	               String trade_no = (String) params.get("out_trade_no"); //商户订单号
	               String out_trade_no = (String) params.get("transaction_id"); //微信订单号
	        	   record(trade_no,"Wxpay",out_trade_no);
	           }
	           result = "SUCCESS";
	       } catch (Exception e){
	    	   e.printStackTrace();
	    	   logger.error("weixin callback error:"+e.getMessage());
	       }
		   
	       try {
				response.getWriter().write(result);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	public static void main(String[] args) {
		
		JSONObject job = JSONObject.parseObject("{\"environment\":\"Production\",\"receipt\":{\"in_app\":[{\"transaction_id\":\"520000564489383\",\"original_purchase_date\":\"2020-04-08 15:32:42 Etc/GMT\",\"quantity\":\"1\",\"original_transaction_id\":\"520000564489383\",\"purchase_date_pst\":\"2020-04-08 08:32:42 America/Los_Angeles\",\"original_purchase_date_ms\":\"1586359962000\",\"purchase_date_ms\":\"1586359962000\",\"product_id\":\"com.fiftyDegrees.member002\",\"original_purchase_date_pst\":\"2020-04-08 08:32:42 America/Los_Angeles\",\"is_trial_period\":\"false\",\"purchase_date\":\"2020-04-08 15:32:42 Etc/GMT\"}],\"adam_id\":1465685810,\"receipt_creation_date\":\"2020-04-08 15:32:42 Etc/GMT\",\"original_application_version\":\"3\",\"app_item_id\":1465685810,\"original_purchase_date_ms\":\"1586358860000\",\"request_date_ms\":\"1586359967126\",\"original_purchase_date_pst\":\"2020-04-08 08:14:20 America/Los_Angeles\",\"original_purchase_date\":\"2020-04-08 15:14:20 Etc/GMT\",\"receipt_creation_date_pst\":\"2020-04-08 08:32:42 America/Los_Angeles\",\"receipt_type\":\"Production\",\"bundle_id\":\"com.wcs.fiftyDegrees\",\"receipt_creation_date_ms\":\"1586359962000\",\"request_date\":\"2020-04-08 15:32:47 Etc/GMT\",\"version_external_identifier\":833775674,\"request_date_pst\":\"2020-04-08 08:32:47 America/Los_Angeles\",\"download_id\":92056993729938,\"application_version\":\"3\"},\"status\":0}"); 
		String status = job.getString("status");
		if (status.equals("0")){
			
			//VipPackage vipPackage = VipPackage.dao.findById(1);

			com.alibaba.fastjson.JSONArray in_app = job.getJSONArray("in_app");
			if (in_app.size() == 0) {
				APIJSON.result(6666);
				return;
			} else {
				String product_id = in_app.getJSONObject(0).getString("product_id");
//				if (!product_id.equals(vipPackage.getStr("apple_pay_id"))) {
//					APIJSON.result(6666);
//					return;
//				}
			}
			
			Long user_id = 140901L;
			String order_num = Toolkit.newTradeNo();
			VipRecord download_vip = VipRecord.dao.findFirst("select id from vip_record where download_id = " + job.getJSONObject("receipt").getLong("download_id")+ " order by id desc limit 1 ");
			if(download_vip != null){
				APIJSON.result(6012);
				return;
			}
			
		}
		/*
		Map<String,String> params = new HashMap<String,String>();
		params.put("gmt_create", "2020-02-25 16:35:30");
		params.put("charset", "utf-8");
		params.put("seller_email", "925393329@qq.com");
		params.put("subject", "会员  6个月 298.0元");
		params.put("sign", "gJ1QBG+votQIvSvJ990mekysz/BFy+oMCtZGzHj8XsVi9gDLNLuqAKM1AJwscCqWB7XKcpdusnKUU5H+XZCEnpyyxpegU2+mcQOgsrVYZWwB4BkvL0kpqB4tJzn8zauaWH37itOsxUmMlvQzogPdBsl5Mk9kJinaN0DWf8lSSP7kyrudMXXmf2QDKO0fRPDCwi8vetpBbe4UVp71MEs4IR9+G/nO1VnzbVKrwu1hK6bVPtCdvHi+8Jt12fi+FUH9pMyfeTRJeri/ujG/EHUoAtcbUtQAMD5xaZ0hsIk0vaU/d4LNIjefUg6QyVvkiOXhX/EXuZy++GAbremwnpD7PA==");
		params.put("body", "会员  6个月 298.0元");
		params.put("buyer_id", "2088002683567344");
		params.put("invoice_amount", "0.01");
		params.put("notify_id", "2020022500222163531067341441185270");
		params.put("amount", "0.01");
		params.put("fund_bill_list", "[{\"\":\"\",\"\":\"ALIPAYACCOUNT\"}]");
		params.put("notify_type", "trade_status_sync");
		params.put("trade_status", "TRADE_SUCCESS");
		params.put("app_id", "2019051764991555");
		params.put("buyer_pay_amount", "0.01");
		params.put("sign_type", "RSA2");
		params.put("seller_id", "2088531254487135");
		params.put("gmt_payment", "2020-02-25 16:35:31");
		params.put("notify_time", "2020-02-25 16:35:31");
		params.put("version", "1.0");
		params.put("out_trade_no", "826196440156850020779715");
		params.put("total_amount", "0.01");
		params.put("trade_no", "826196440156850020779715");
		params.put("auth_app_id", "2019051764991555");
		params.put("buyer_logon_id", "892***@qq.com");
		params.put("point_amount", "0.00");
		//"{gmt_create=2020-02-25 16:35:30, charset=utf-8, seller_email=925393329@qq.com, subject=会员  6个月 298.0元, sign=gJ1QBG+votQIvSvJ990mekysz/BFy+oMCtZGzHj8XsVi9gDLNLuqAKM1AJwscCqWB7XKcpdusnKUU5H+XZCEnpyyxpegU2+mcQOgsrVYZWwB4BkvL0kpqB4tJzn8zauaWH37itOsxUmMlvQzogPdBsl5Mk9kJinaN0DWf8lSSP7kyrudMXXmf2QDKO0fRPDCwi8vetpBbe4UVp71MEs4IR9+G/nO1VnzbVKrwu1hK6bVPtCdvHi+8Jt12fi+FUH9pMyfeTRJeri/ujG/EHUoAtcbUtQAMD5xaZ0hsIk0vaU/d4LNIjefUg6QyVvkiOXhX/EXuZy++GAbremwnpD7PA==, body=会员  6个月 298.0元, buyer_id=2088002683567344, invoice_amount=0.01, notify_id=2020022500222163531067341441185270, fund_bill_list=[{\"amount\":\"0.01\",\"fundChannel\":\"ALIPAYACCOUNT\"}], notify_type=trade_status_sync, trade_status=TRADE_SUCCESS, receipt_amount=0.01, app_id=2019051764991555, buyer_pay_amount=0.01, sign_type=RSA2, seller_id=2088531254487135, gmt_payment=2020-02-25 16:35:31, notify_time=2020-02-25 16:35:31, version=1.0, out_trade_no=826196440156850020779715, total_amount=0.01, trade_no=2020022522001467341422777490, auth_app_id=2019051764991555, buyer_logon_id=892***@qq.com, point_amount=0.00}"
		
		try {
			
			boolean flag = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key,"utf-8","RSA2");
			System.out.println(flag);
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		/*
		com.alibaba.fastjson.JSONArray in_app = JSONArray.parseArray("[{\"transaction_id\": \"400000612705355\",\"original_purchase_date\": \"2019-11-19 06:44:34 Etc/GMT\",\"quantity\": \"1\",\"original_transaction_id\": \"400000612705355\",\"purchase_date_pst\": \"2019-11-18 22:44:34 America/Los_Angeles\",\"original_purchase_date_ms\": \"1574145874000\",\"purchase_date_ms\": \"1574145874000\",\"product_id\": \"com.fiftyDegrees.member001\",\"original_purchase_date_pst\": \"2019-11-18 22:44:34 America/Los_Angeles\",\"is_trial_period\": \"false\",\"purchase_date\": \"2019-11-19 06:44:34 Etc/GMT\"}]");
		if (in_app.size() == 0) {
			System.out.println(666);
		} else {
			String product_id = in_app.getJSONObject(0).getString("product_id");
			if (!product_id.equals("com.fiftyDegrees.member001")) {
				System.out.println(6666);
			}
		}
		System.out.println(8888);
		
		
//		JSONObject job = JSONObject.parseObject("{\"environment\":\"Production\",\"receipt\":{\"in_app\":[],\"adam_id\":1465685810,\"receipt_creation_date\":\"2019-11-17 19:55:00 Etc/GMT\",\"original_application_version\":\"12\",\"app_item_id\":1465685810,\"original_purchase_date_ms\":\"1574020500000\",\"request_date_ms\":\"1574021919807\",\"original_purchase_date_pst\":\"2019-11-17 11:55:00 America/Los_Angeles\",\"original_purchase_date\":\"2019-11-17 19:55:00 Etc/GMT\",\"receipt_creation_date_pst\":\"2019-11-17 11:55:00 America/Los_Angeles\",\"receipt_type\":\"Production\",\"bundle_id\":\"com.wcs.fiftyDegrees\",\"receipt_creation_date_ms\":\"1574020500000\",\"request_date\":\"2019-11-17 20:18:39 Etc/GMT\",\"version_external_identifier\":831463258,\"request_date_pst\":\"2019-11-17 12:18:39 America/Los_Angeles\",\"download_id\":61060054682656,\"application_version\":\"12\"},\"status\":0}"); 
//		String status = job.getString("status");
		
//		System.out.println(job.getJSONObject("receipt").getLongValue("download_id"));
 * */
	}
}
